package com.powervision.thirdlogindemo.utils

import android.app.Activity
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.powervision.thirdlogindemo.R
import com.powervision.thirdlogindemo.bean.FaceBookLoginInfoBean
import com.powervision.thirdlogindemo.utils.Constant.Companion.mFaceBookCancelCode
import com.powervision.thirdlogindemo.utils.Constant.Companion.mFaceBookFailedCode
import com.powervision.thirdlogindemo.utils.Constant.Companion.mFaceBookSuccessCode

/**
 * @auth: njb
 * @date: 2021/10/25 17:53
 * @desc: FaceBook登录工具类
 */
open class FaceBookLoginUtils(
    var activity: Activity,
    private var callbackManager: CallbackManager
) {
    private val requestSuccessCode by lazy { mFaceBookSuccessCode }
    private val requestCancelCode by lazy { mFaceBookCancelCode }
    private val requestFailedCode by lazy { mFaceBookFailedCode }
    private val infoBean by lazy { FaceBookLoginInfoBean() }
    private var mFaceBookLoginListener: FaceBookLoginListener? = null
    private var loginManager: LoginManager = LoginManager.getInstance()
    private val permissions: List<String>

    init {
        callbackManager = CallbackManager.Factory.create()
        loginManager.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(result: LoginResult?) {
                activity.setResult(requestSuccessCode)
                //登录成功，获取用户信息
                result?.accessToken?.let { getLoginInfo(it) }
            }

            override fun onCancel() {
                activity.setResult(requestCancelCode)
                mFaceBookLoginListener?.onLoginCancel(activity.getString(R.string.login_cancel))
            }

            override fun onError(error: FacebookException?) {
                activity.setResult(requestFailedCode)
                mFaceBookLoginListener?.onLoginFailed(activity.getString(R.string.login_failed))
            }

        })
        permissions = listOf(
            "email",
            "user_likes",
            "user_status",
            "user_photos",
            "user_birthday",
            "public_profile",
            "user_friends"
        );
    }

    /**
     * 登陆
     */
    fun login() {
        loginManager.logIn(activity, permissions)
    }

    /**
     * 退出登录
     */
    fun loginOut() {
        val logout = activity.resources.getString(R.string.com_facebook_loginview_log_out_action)
        val cancel = activity.resources.getString(R.string.com_facebook_loginview_cancel_action)
        val message: String
        val profile: Profile = Profile.getCurrentProfile()
        message = if (profile.name != null) {
            java.lang.String.format(
                activity.resources.getString(
                    R.string.com_facebook_loginview_logged_in_as
                ),
                profile.name
            )
        } else {
            activity.resources.getString(
                R.string.com_facebook_loginview_logged_in_using_facebook
            )
        }
        val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
        builder.setMessage(message)
            .setCancelable(true)
            .setPositiveButton(logout) { _, _ ->
                loginManager.logOut()
            }
            .setNegativeButton(cancel, null)
        builder.create().show()
    }


    /**
     * 用户是否处在登陆状态
     */
    fun isLogin(): Boolean {
        val accessToken = AccessToken.getCurrentAccessToken()
        return accessToken != null && !accessToken.isExpired
    }

    /**
     * 获取用户信息
     */
    private fun getLoginInfo(accessToken: AccessToken) {
        val request = GraphRequest.newMeRequest(
            accessToken
        ) { `object`, _ ->
            `object`.run {
                val id = optString("id") //比如:13813813888
                val name = optString("name") //比如：Zhang San
                val gender = optString("gender") //性别：比如 male （男）  female （女）
                val email = optString("email") //邮箱：比如：11111@qq.com
                //获取用户头像
                val picture = optJSONObject("picture")
                val data = picture.optJSONObject("data")
                val photoUrl = data.optString("url")
                //获取地域信息
                val locale = optString("locale") //zh_CN 代表中文简体
                infoBean.id = id
                infoBean.name = name
                infoBean.email = email
                infoBean.gender = gender
                infoBean.picture = picture.toString()
                infoBean.data = data.toString()
                infoBean.photo = photoUrl
                infoBean.locale = locale
                infoBean.let { mFaceBookLoginListener?.onLoginSuccess(it) }
            }
        }
        val parameters = Bundle()
        parameters.putString(
            "fields",
            "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name"
        )
        request.parameters = parameters
        request.executeAsync()
    }

    open fun getCallbackManager(): CallbackManager? {
        return callbackManager
    }


    open fun setFaceBookLoginListener(faceBookLoginListener: FaceBookLoginListener) {
        this.mFaceBookLoginListener = faceBookLoginListener
    }

    interface FaceBookLoginListener {
        fun onLoginSuccess(infoBean: FaceBookLoginInfoBean)

        fun onLoginFailed(message: String)

        fun onLoginCancel(message: String)

        fun onLogoutSuccess()

        fun onLogoutFailed()
    }
}